Plotly

Why use interactive graphics?

  • Zooming
  • Silencing
  • Hovering
  • Sliding
  • Filtering

Difference between interactive and animated graphs

  • interactive graphs allow the user to manipulate different features of the graph

plotly Resources

library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.3.6     ✔ purrr   0.3.4
## ✔ tibble  3.1.7     ✔ dplyr   1.0.9
## ✔ tidyr   1.2.0     ✔ stringr 1.4.0
## ✔ readr   2.1.2     ✔ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
library(plotly)
## 
## Attaching package: 'plotly'
## 
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## 
## The following object is masked from 'package:stats':
## 
##     filter
## 
## The following object is masked from 'package:graphics':
## 
##     layout
# read in 'wine.csv' data
wine <- read.csv('data/wine.csv')

head(wine)
##   Type Alcohol Malic  Ash Alcalinity Magnesium Phenols Flavanoids Nonflavanoids
## 1    1   14.23  1.71 2.43       15.6       127    2.80       3.06          0.28
## 2    1   13.20  1.78 2.14       11.2       100    2.65       2.76          0.26
## 3    1   13.16  2.36 2.67       18.6       101    2.80       3.24          0.30
## 4    1   14.37  1.95 2.50       16.8       113    3.85       3.49          0.24
## 5    1   13.24  2.59 2.87       21.0       118    2.80       2.69          0.39
## 6    1   14.20  1.76 2.45       15.2       112    3.27       3.39          0.34
##   Proanthocyanins Color  Hue Dilution Proline
## 1            2.29  5.64 1.04     3.92    1065
## 2            1.28  4.38 1.05     3.40    1050
## 3            2.81  5.68 1.03     3.17    1185
## 4            2.18  7.80 0.86     3.45    1480
## 5            1.82  4.32 1.04     2.93     735
## 6            1.97  6.75 1.05     2.85    1450
wine$Type <- as.factor(wine$Type)

Convert Static Graphs to Interactive Graphs Using ggplotly

Let’s look at a static graph comparing flavanoids to proline

static_plot <- wine %>%
  ggplot(aes(Flavanoids, Proline, color = Type)) +
  geom_point() +
  theme_minimal() +
  scale_color_manual(values = c("#00AFBB", "#E7B800", "#FC4E07"))

static_plot

How to create a plotly object

  • There are two main approaches to initialize a plotly object:

    • transforming a ggplot2 object with ggplotly()
    • setting up aesthetics mappings with plot_ly() directly

Today’s focus ggplotly()

# Create an interactive plot of Flavonoids vs Proline

ggplotly(static_plot)

Notes

Interactive plots are great!
Bad Design = Bad Interactive Plots
Follow data-viz best practices

Bar Plot

g <- ggplot(data = wine, aes(x = Type, fill = Type)) + 
     geom_bar(fill = c("#00AFBB", "#E7B800", "#FC4E07")) +
     theme_classic() 

ggplotly(g)

If you want the bar in descending order

g.5 <- count(wine, Type) %>% 
       ggplot(aes(x = reorder(Type, -n), y = n)) +
       geom_bar(fill = c("#00AFBB", "#E7B800", "#FC4E07"), stat = 'identity') +
       theme_classic() +
       xlab('Type')
     
ggplotly(g.5)

Histogram

g2 <- ggplot(wine, aes(x = Flavanoids, fill = as.factor(Type))) + 
      geom_histogram(bins = 15, alpha = 0.6) +
      theme_minimal() +
      scale_fill_manual(values = c("#00AFBB", "#E7B800", "#FC4E07")) 

ggplotly(g2)

Scatterplot

g4 <- ggplot(wine, aes(x = Flavanoids, y = Proline, color = as.factor(Type))) + 
      geom_point() + 
      geom_smooth(method="loess", formula=y~x, se=F) + 
      scale_color_manual(values = c("#00AFBB", "#E7B800", "#FC4E07"), name = 'Type') +
      theme_bw() 

ggplotly(g4)
g5 <- ggplot(wine, aes(x = Flavanoids, y = Proline, color = as.factor(Type))) + 
      geom_point() + 
      geom_smooth(method="lm", formula=y~x, se=F) + 
      scale_color_manual(values = c("#00AFBB", "#E7B800", "#FC4E07"), name = 'Type') +
      theme_bw()

ggplotly(g5)

Creating interactive graphs directly in plot_ly

import plotly

library(plotly)

Bar plot

wine %>% mutate(fType = as.factor(Type)) %>%
  count(fType) %>% #using dplyr create frequency table
  plot_ly(x = ~fType, y = ~n) %>% # initialize graph in plotly, use ~ for aes mappings
  add_bars() %>% #set graph as bar chart
  layout(title = "Freq. of Wine Soil Type",
         xaxis = list(title = "Type"),
         yaxis = list(title = "Frequency"))

Reorder columns

wine %>% mutate(fType = as.factor(Type)) %>%
  count(fType) %>% #using dplyr create frequency table
  mutate(fType = fct_reorder(fType, n, .desc = TRUE)) %>% #order for largest to smallest
  plot_ly(x = ~fType, y = ~n) %>% # initialize graph in plotly, use ~ for aes mappings
  add_bars() %>% #set graph as bar chart
  layout(title = "Freq. of Wine Soil Type",
         xaxis = list(title = "Type"),
         yaxis = list(title = "Frequency"))

Basic Histogram

g6 <- plot_ly(wine, x = ~Flavanoids, type = "histogram")

g6

Flavanoids by Type Histogram

Type1 <- wine %>% filter(Type == 1)
Type2 <- wine %>% filter(Type ==2)
Type3 <- wine %>% filter(Type == 3)
g7 <- plot_ly(alpha = 0.4) %>%
  add_histogram(x = ~Type1$Flavanoids,
                name = 'Type 1',
                opacity = 0.6, 
                marker = list(color = "#00AFBB",
                              alpha = 0.6,
                              line = list(color = "lightgray",
                              width = 2))) %>%
  add_histogram(x = ~Type2$Flavanoids,
                name = 'Type 2',
                opacity = 0.6,
                marker = list(color = "#E7B800",
                              line = list(color = "lightgray",
                              width = 2))) %>%
  add_histogram(x = ~Type3$Flavanoids, 
                name = 'Type 3',
                opacity = 0.6,
                marker = list(color = "#FC4E07",
                              line = list(color = "lightgray",
                              width = 2))) %>%
  layout(barmode = 'overlay',
         title = 'Histogram of flavanoids by soil type',
         xaxis = list(title = 'flavanoids',
                      zeroline = FALSE),
         yaxis = list(title = 'count'))

g7

Scatter plot

fig <- plot_ly(type = 'scatter', mode = 'markers') 

fig <- fig %>%
  add_trace(
    x = Type1$Flavanoids,
    y = Type1$Proline,
    opacity = 0.5,
    marker = list(
      color = "#00AFBB",
      size = 7,
      line = list(
        color = 'lightgray',
        width = .5
      )
    ),
    name = 'Type 1'
  ) 

fig <- fig %>%
  add_trace(
    x = Type2$Flavanoids,
    y = Type2$Proline,
    marker = list(
      color = "#E7B800",
      size = 7,
      line = list(
        color = 'lightgray',
        width = .5
      )
    ),
    name = 'Type 2'
  )

fig <- fig %>%
  add_trace(
    x = Type3$Flavanoids,
    y = Type3$Proline,
    marker = list(
      color = "#FC4E07",
      size = 7,
      line = list(
        color = 'lightgray',
        width = .5
      )
    ),
    name = 'Type 3'
  )

fig <- fig %>%
  layout(title = 'Scatterplot of Flavanoids & Proline',
         xaxis = list(title = 'flavanoids',
                      zeroline = FALSE),
         yaxis = list(title = 'proline'))
fig

3D Scatterplot

fig2 <- plot_ly(type = 'scatter3d', mode = 'markers') 
fig2 <- fig2 %>%
  add_trace(
    x = Type1$Flavanoids,
    y = Type1$Proline,
    z = Type1$Alcalinity,
    opacity = 0.5,
    marker = list(
      color = "#00AFBB",
      size = 7,
      line = list(
        color = 'lightgray',
        width = .5
      )
    ),
    name = 'Type 1'
  ) 

fig2 <- fig2 %>%
  add_trace(
    x = Type2$Flavanoids,
    y = Type2$Proline,
    z = Type2$Alcalinity,
    marker = list(
      color = "#E7B800",
      size = 7,
      line = list(
        color = 'lightgray',
        width = .5
      )
    ),
    name = 'Type 2'
  )

fig2 <- fig2 %>%
  add_trace(
    x = Type3$Flavanoids,
    y = Type3$Proline,
    z = Type3$Alcalinity,
    marker = list(
      color = "#FC4E07",
      size = 7,
      line = list(
        color = 'lightgray',
        width = .5
      )
    ),
    name = 'Type 3'
  )

axx <- list(
  title = "flavanoids"
)

axy <- list(
  title = "proline"
)

axz <- list(
  title = "alcalinity"
)

fig2 <- fig2 %>%
  layout(title = 'Scatterplot of Flavanoids, Proline & Alcalinity',
         scene = list(xaxis = axx,
                      yaxis = axy,
                      zaxis = axz))

fig2

Line Plot

(From plotly examples)

library(plyr)
## ------------------------------------------------------------------------------
## You have loaded plyr after dplyr - this is likely to cause problems.
## If you need functions from both plyr and dplyr, please load plyr first, then dplyr:
## library(plyr); library(dplyr)
## ------------------------------------------------------------------------------
## 
## Attaching package: 'plyr'
## The following objects are masked from 'package:plotly':
## 
##     arrange, mutate, rename, summarise
## The following objects are masked from 'package:dplyr':
## 
##     arrange, count, desc, failwith, id, mutate, rename, summarise,
##     summarize
## The following object is masked from 'package:purrr':
## 
##     compact
#create date
tg <- ddply(ToothGrowth, c("supp", "dose"), summarise, length=mean(len))

# create figure
fig <- plot_ly(tg, x = ~dose, y = ~length, type = 'scatter', mode = 'lines', linetype = ~supp, color = I('black')) 

fig <- fig %>% layout(title = 'The Effect of Vitamin C on Tooth Growth in Guinea Pigs by Supplement Type',
         xaxis = list(title = 'Dose in milligrams/day'),
         yaxis = list (title = 'Tooth length'))

fig